/*   
 * ???????FinanceController.java
 * ???????Copy Ruantu??  
 * ??????????????  
 * ????????MengFanding?? 
 * ??????2017 ????2:45:11
 * ????????????????  
 * ??????????????????  
 */

package com.ruantu.clothing.controller.finance;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpSession;

import com.ruantu.clothing.entity.*;
import com.ruantu.clothing.entity.finance.Period;
import com.ruantu.clothing.entity.report.Foot;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruantu.clothing.entity.easyuientity.DataGridMsg;
import com.ruantu.clothing.entity.finance.Finance;
import com.ruantu.clothing.entity.finance.FinanceRecord;
import com.ruantu.clothing.entity.finance.FinanceTransaction;
import com.ruantu.clothing.service.finance.FinanceService;

/**
 * FinanceController
 */

@Controller
@RequestMapping("/finance")
public class FinanceController {

    private static Logger log = LoggerFactory.getLogger(FinanceController.class);

    @Autowired
    private FinanceService financeService;

    /***
     * 账期必填
     * @param name
     * @return
     */
    @RequestMapping(value = "/period", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponseMessage startPeriod(String name) {

        JsonResponseMessage msg = new JsonResponseMessage();

        if (name == null || "".equals(name)) {
            msg.setCode(500000);
            msg.setMsg("账期名称必填");
            return msg;
        }

        try {
            financeService.startNewPeriod(name);
            log.info("开启一个新账期：[{}] ", name);
        } catch (Exception e) {
            log.info("开启一个新账期：[{}] 失败", name);
            msg.setCode(500000);
            msg.setMsg(e.getMessage());
        }

        return msg;
    }

    @RequestMapping(value = "/period", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponseMessage showPeriods() {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            msg.setData(financeService.showPeriodList());
        } catch (Exception e) {
            msg.setMsg(e.getMessage());
            msg.setCode(50000);
        }
        return msg;
    }

    @RequestMapping(value = "/finances", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponseMessage findFinanceInThisPeriod(String periodId, PageBean page, HttpSession session) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            String jgid = "" + user.getJgid();// FIXME FIXME 这里从session中取出当前用户的机构id
            DataGridMsg data = new DataGridMsg();
            List<Finance> list = financeService.findFinancePeriod(jgid, periodId, page);
            data.setRows(list);
            data.setTotal(page.getTotal());
            msg.setData(data);
        } catch (Exception e) {

            e.printStackTrace();
        }

        return msg;
    }

    @RequestMapping(value = "/financerecord", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponseMessage findFinanceRecords(String id, PageBean page) {
        JsonResponseMessage msg = new JsonResponseMessage();
        DataGridMsg data = new DataGridMsg();
        List<FinanceRecord> list = financeService.findByFinanceKey(id, page);
        data.setRows(list);
        data.setTotal(page.getTotal());
        msg.setData(data);
        return msg;
    }

    //?????  finlrecode
    @RequestMapping(value = "/record", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponseMessage record(FinanceRecord record, HttpSession session) {
        JsonResponseMessage msg = new JsonResponseMessage();
        User user = (User) session.getAttribute("info");

        // FIXME 从session中获得id
        String jgid = "" + user.getJgid();//WW
        record.setGsjg(jgid);
        try {
            financeService.addFinanceRecord(record);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            msg.setCode(50000);
            msg.setMsg(e.getMessage());
        }
        return msg;
    }


    /***
     * 添加收支记录
     * @param transaction
     * @param session
     * @return
     */
    @RequestMapping(value = "/transaction", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponseMessage transaction(FinanceTransaction transaction, HttpSession session) {
        JsonResponseMessage msg = new JsonResponseMessage();
        User user = (User) session.getAttribute("info");
        //session 里机构id
        String jgid = "" + user.getJgid();//WWW
        transaction.setWldwtype(1);
        transaction.setGsjg(jgid);
        transaction.setJbr(user.getNikeName());
        try {
            financeService.payOrReceive(transaction);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
            msg.setCode(50000);
            msg.setMsg(e.getMessage());
        }
        return msg;
    }

    @RequestMapping("/transactionRecord")
    @ResponseBody
    public JsonResponseMessage transaction(PageBean page, Integer hl, String lsh, HttpSession session) {
        JsonResponseMessage msg = new JsonResponseMessage();
        User user = (User) session.getAttribute("info");
        String gsjg = "" + user.getJgid();//WW
        try {
            List<FinanceTransaction> list = financeService.findByLSHPage(hl, lsh, gsjg, page);
            /*DataGridMsg data = new DataGridMsg();*/
            /*data.setRows(list);
            data.setTotal(page.getTotal());*/
            msg.setRows(list);
            msg.setTotal(page.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);

            msg.setCode(50000);
            msg.setMsg(e.getMessage());
        }
        return msg;
    }


    /**
     * 小票打印查询
     *
     * @param
     * @return
     */
    @RequestMapping("/findallkehu")
    @ResponseBody
    public JsonResponseMessage findSaleXiaopiao() {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            List<KeHu> kehuList = financeService.selectAllKeHuService();
            if (kehuList != null) {
                msg.setMsg("获取数据成功!");
                msg.setCode(200);
                msg.setData(kehuList);
            } else {
                msg.setData("暂无数据");
                msg.setCode(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        }
        return msg;
    }


    /**
     * 小票打印查询
     *
     * @param
     * @return
     */
    @RequestMapping("/findperiodlist")
    @ResponseBody
    public JsonResponseMessage findPeriodList() {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            List<Period> periodList = financeService.selectPeriodListService();
            if (periodList != null) {
                msg.setMsg("获取数据成功!");
                msg.setCode(200);
                msg.setData(periodList);
            } else {
                msg.setData("暂无数据");
                msg.setCode(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        }
        return msg;
    }


    /**
     * 总账报表
     *
     * @param
     * @return
     */
    @RequestMapping("/findzzlist")
    @ResponseBody
    public JsonResponseMessage selectZZReportListService(PageBean page) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            List<Finance> periodList = financeService.selectZZReportListService(page);
            if (periodList != null) {
                msg.setMsg("获取数据成功!");
                msg.setCode(200);
                msg.setRows(periodList);
                msg.setTotal(page.getTotal());
            } else {
                msg.setData("暂无数据");
                msg.setCode(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        }
        return msg;
    }


    /**
     * 总账明细报表
     *
     * @param
     * @return
     */
    @RequestMapping("/findzzmxlist")
    @ResponseBody
    public JsonResponseMessage selectZZMXReportListController(PageBean page) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            List<ZZMX> periodList = financeService.selectZZMXReportListService(page);
            if (periodList != null) {
                msg.setMsg("获取数据成功!");
                msg.setCode(200);
                msg.setRows(periodList);
                msg.setTotal(page.getTotal());
            } else {
                msg.setData("暂无数据");
                msg.setCode(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        }
        return msg;
    }

    /**
     * 根据机构jgid查询
     *
     * @param session
     * @param session
     * @return
     */
    @RequestMapping(value = "/selectByJgid", method = RequestMethod.GET)
    @ResponseBody
    public List<FinanceTransaction> selectByJgid(HttpSession session) {
        try {
            User user = (User) session.getAttribute("info");
            String jgid = "" + user.getJgid();
            return financeService.selectByJgid(jgid);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @RequestMapping("/findnaj")
    @ResponseBody
    public JsonResponseMessage getNAJ(HttpSession session) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            List<YearAndSeason> periodList = financeService.findNAJ(user.getJgid());
            if (periodList != null) {
                msg.setMsg("获取数据成功!");
                msg.setCode(200);
                msg.setData(periodList);

            } else {
                msg.setData("暂无数据");
                msg.setCode(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        }
        return msg;
    }


    @RequestMapping("/zongzhangdaochu")
    @ResponseBody
    public ResponseEntity<byte[]> ZongHZhangDaoChu(HttpSession session, PageBean page, ServletOutputStream out) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            HSSFWorkbook wb = financeService.selectZZReportListDaoChuService(page);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
            wb.write(out);
            outByteStream.flush();
            outByteStream.close();
            return new ResponseEntity<byte[]>(outByteStream.toByteArray(), headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /***
     * 总账明细导出
     * @param session
     * @param page
     * @param out
     * @return
     */

    @RequestMapping("/zongzhangdaochumx")
    @ResponseBody
    public ResponseEntity<byte[]> ZongHZhangDaoChuMX(HttpSession session, PageBean page, ServletOutputStream out) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            HSSFWorkbook wb = financeService.selectZZMXReportListDaoChuServicer(page);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
            wb.write(out);
            outByteStream.flush();
            outByteStream.close();
            return new ResponseEntity<byte[]>(outByteStream.toByteArray(), headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /***
     * 对账单数据获取
     * @param session
     * @param page
     * @return
     */
    @RequestMapping("/findAccount")
    @ResponseBody
    public JsonResponseMessage findAccount(HttpSession session, PageBean page) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            List<ZZMX> accountList = financeService.financeAccountService(page);
            if (accountList != null) {
                msg.setMsg("获取数据成功!");
                msg.setCode(200);
                msg.setRows(accountList);
                msg.setTotal(page.getFoot().getTotal());
                List<Foot> foot =new ArrayList<>();
                foot.add(page.getFoot());
                msg.setFooter(foot);
            } else {
                msg.setRows("暂无数据");
                msg.setCode(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        }
        return msg;
    }

    /****
     * 销售报表导出
     * @param session
     * @param page
     * @param out
     * @return
     */
    @RequestMapping("/Account_report")
    @ResponseBody
    public ResponseEntity<byte[]> Account_report(HttpSession session, PageBean page, ServletOutputStream out) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            HSSFWorkbook wb =financeService.financeAccountReportService(page);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
            wb.write(out);
            outByteStream.flush();
            outByteStream.close();
            return new ResponseEntity<byte[]>(outByteStream.toByteArray(), headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }




}
